<template>
    <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
        <el-steps :active="active">
            <template v-for="(step, index) in steps" :key="index">
                <el-step>
                    <template #title>
                        <span class="step-title" @click="active = step.value">{{ step.title }}</span>
                    </template>
                </el-step>
            </template>
        </el-steps>

        <div v-show="active === 1" class="step1">
            <el-form-item label="节点名称">
                <el-input v-model="form.nodeName"></el-input>
            </el-form-item>
            <el-form-item label="节点ID">
                <el-input v-model="form.typeConcatName" disabled></el-input>
            </el-form-item>
            <el-form-item label="数据所在节点">
                <el-select v-model="form.node" @change="nodeChange">
                    <el-option
                        v-for="item in nodeList"
                        :key="item.id"
                        :label="`${item.nodeName} (${item.name})`"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 2">下一步</el-button>
            </dialog-footer>

        </div>
        <div v-show="active === 2" class="step2">
            <div style="margin-bottom: 10px;">
                <el-button
                    type="primary"
                    size="small"
                    @click="addField"
                >新增字段</el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="batchDelete"
                    :disabled="selectedRows.length === 0"
                >删除选中</el-button>

            </div>
            <el-table :data="form.fields.field" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="30"/>
                <el-table-column label="序号" width="50" header-align="center" align="center">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="in_stream_name" label="输入字段" width="150">
                    <template #default="scope">
                        <el-select v-model="scope.row.in_stream_name">
                            <el-option
                                v-for="item in form.fieldList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.name">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="out_stream_name" label="输出字段" width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.out_stream_name"/>
                    </template>
                </el-table-column>
                <el-table-column prop="use_regex" label="使用正则" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.use_regex" active-value="Y" inactive-value="N"/>
                    </template>
                </el-table-column>
                <el-table-column prop="replace_string" label="源字符串" width="240">
                    <template #default="scope">
                        <el-input v-model="scope.row.replace_string"/>
                    </template>
                </el-table-column>
                <el-table-column prop="replace_by_string" label="目标字符串" width="180">
                    <template #default="scope">
                        <el-input v-model="scope.row.replace_by_string"/>
                    </template>
                </el-table-column>
                <el-table-column prop="whole_word" label="全字段匹配" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.whole_word" active-value="yes" inactive-value="no"/>
                    </template>
                </el-table-column>
                <el-table-column prop="case_sensitive" label="匹配大小写" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.case_sensitive" active-value="yes" inactive-value="no"/>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button
                            type="danger"
                            size="small"
                            @click="deleteField(scope.$index)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 1">上一步</el-button>
            </dialog-footer>
        </div>
    </el-form>
</template>

<script setup>
import {defineComponent, ref, onMounted, reactive, watch, computed} from 'vue';
import {flowServiceStore} from '@data/store/flow';

const flowCount = flowServiceStore();
import {storeToRefs} from 'pinia';

const {flowData} = storeToRefs(flowCount);
import {search as datasourceList} from '@data/api/data/datasource'
import { selectTables, selectSchema, selectColumns, selectTableInfo, selectColumnsByQuerySql } from '@data/api/data/datacollection'

import {cloneDeep} from "lodash-es";
import {ElMessage} from "element-plus";

defineComponent({
    name: 'ReplaceString',
});
const props = defineProps({
    detailObject: {
        type: Object,
        default: () => {
        },
    },
})
const nodeList = computed(() => {
    return Object.entries(flowData.value)
        .filter(([nodeId, node]) => nodeId !== props.detailObject.id && node.type !== 'edge' && node.type !== 'Edge')
        .map(([id, node]) => ({
            id,
            ...node
        }))
})
console.log(nodeList.value)
const steps = ref([
    { value: 1, title: '基础属性' },
    { value: 2, title: '字符串替换' }
]);
const active = ref(1);

const loading = ref(false);

const form = reactive({
    nodeName: '',
    name: '',
    type: 'ReplaceString',
    copies: 1,

    node: '',
    description: '',

    fieldList: [],
    fields: {
        field: []
    },

    custom_distribution: '',
    partitioning: {
        method: 'none',
        schema_name: ''
    },
    distribute: 'Y',
    GUI: {
        xloc: 1,
        yloc: 1,
        draw: 'Y'
    }
});

const emit = defineEmits(['cancel']);

onMounted(() => {
    form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
    form.node = flowData.value[props.detailObject.id]?.node || '';
    form.fields.field = flowData.value[props.detailObject.id]?.fields?.field || [];
    form.description = flowData.value[props.detailObject.id]?.description || '';
    if(form.node){
        nodeChange(form.node);
    } else {
        form.fields.field = [
            {
                in_stream_name: '',
                out_stream_name: '',
                use_regex: 'no',
                replace_string: '',
                replace_by_string: '',
                set_empty_string: 'N',
                replace_field_by_string: '',
                whole_word: 'no',
                case_sensitive: 'no',
                is_unicode: 'no',
            }
        ]
    }

    form.name = props.detailObject.id;
    form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;


})

const nodeChange = (value) => {
    nodeList.value.forEach((item) => {
        if (item.id === value && item.fields?.field) {
            form.fieldList = cloneDeep(item.fieldList);
        }
    })
}

const selectedRows = ref([])
// 处理选择变化
const handleSelectionChange = (val) => {
    selectedRows.value = val
}
// 批量删除方法
const batchDelete = () => {
    if (selectedRows.value.length === 0) return
    const indexes = selectedRows.value.map(row =>
        form.fields.field.indexOf(row)
    ).sort((a,b) => b - a)
    indexes.forEach(index => {
        form.fields.field.splice(index, 1)
    })
    selectedRows.value = []
}
const addField = () => {
    form.fields.field.push({
        in_stream_name: '',
        out_stream_name: '',
        use_regex: 'no',
        replace_string: '',
        replace_by_string: '',
        set_empty_string: 'N',
        replace_field_by_string: '',
        whole_word: 'no',
        case_sensitive: 'no',
        is_unicode: 'no',
    });
}
const deleteField = (index) => {
    form.fields.field.splice(index, 1);
}

const submitForm = () => {
    // 执行字段名称替换逻辑
    form.fields.field.forEach(fieldItem => {
        const targetField = form.fieldList.find(
            f => f.name === fieldItem.in_stream_name
        );
        if (targetField && fieldItem.out_stream_name) {
            targetField.name = fieldItem.out_stream_name;
        }
    });

    flowCount.setFlowData({
        ...flowData.value,
        [props.detailObject.id]: {
            ...form,
            name: `${form.type}-${form.name}`,
        }
    })
    console.log(flowData.value);
    emit('cancel');
}
const cancel = () => {
    emit('cancel');
}
</script>

<style scoped>

</style>